package api

import (
	"encoding/json"
	"fmt"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"

	"chaincode/model"
	"chaincode/pkg/utils"
)

func CreateMobileUser(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	//验证参数
	if len(args) != 2 {
		return shim.Error("参数个数不满足！")
	}
	userName := args[0]
	appId := args[1]
	if userName == "" || appId == "" {
		return shim.Error("参数不可以为空！")
	}
	account := model.Account{
		AccountId: appId,
		UserName:  userName,
	}
	//写入账本
	err := utils.WriteLedger(account, stub, model.AccountKey, []string{account.AccountId})
	if err != nil {
		return shim.Error(fmt.Sprintf("写入账本失败：%s", err.Error()))
	}
	accountByte, err := json.Marshal(account)
	if err != nil {
		return shim.Error(fmt.Sprintf("account-key反序列化失败：%s", err.Error()))
	}
	return shim.Success(accountByte)
}
